<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
    <div id="test">

    </div>

    <script type="text/javascript" src="../js/react.development.js"></script>
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <script type="text/javascript" src="../js/prop-types.js"></script>
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <script type="text/babel">
     /*
      1)拆分组件: 拆分界面,抽取组件
      2)实现静态组件: 使用组件实现静态页面效果
      3)实现动态组件
        ① 动态显示初始化数据
        ② 交互功能(从绑定事件监听开始)
     */
     class App extends React.Component {
        // 定义state
        state = {
          todos: ['吃饭1', '睡觉1', '打豆豆1' ]
        }

        // 添加列表
        addTodo = (todo) => {
          this.setState({
            todos: [todo, ...this.state.todos]
          })
        }
        render() {
          return (
            <div> 
              <Add addTodo={this.addTodo} length={this.state.todos.length}/>
              <Todos todos={this.state.todos}/>
            </div>
          )
        }
     }

     // 添加todo
     class Add extends React.Component {
      constructor(props){
        super(props);
        this.myRefs = React.createRef();
      }
      // 添加todo
      add = () => {
        // 获取到文本框的值
        const ipt = this.myRefs.current;

        if (ipt.value.trim()) {
            // 调用APP组件的addTodo方法
          this.props.addTodo(ipt.value)
        }
        
        ipt.value = '';
        ipt.focus();
      }
      render() {
        return (
          <div>
             <input type="text" ref={this.myRefs}/>
             <input type="button" onClick={ this.add } value={"添加 / " + this.props.length} />
          </div>
        )
      }
     }

     // Todos 列表
     function Todos (props) {
       return (
         <ul>
          {
            props.todos.map( (item, index) => <li key={index}>{item}</li> )
          }
         </ul>
       )
     }
     Todos.propTypes = {
       todos: PropTypes.array.isRequired
     }

     // 渲染到页面
     ReactDOM.render(<App />, document.getElementById('test'));
    </script>
</body>
</html>